package com.itheima.question.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.PageVo;
import com.itheima.admin.dto.PageDto;
import com.itheima.admin.dto.QuestionDto;
import com.itheima.admin.vo.QuestionVo;
import com.itheima.common.contants.RedisPicConstants;
import com.itheima.question.mapper.QuestionMapper;
import com.itheima.admin.pojo.Question;
import com.itheima.question.service.IQuestionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class IQuestionServiceImpl implements IQuestionService {
    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${fileServerUrl}")
    private String fileServerUrl;
    @Override
    public boolean addQuestion(QuestionDto questionDto) {
        Question question = new Question();
        BeanUtils.copyProperties(questionDto,question);
        int i = questionMapper.insert(question);
        redisTemplate.opsForSet().add(RedisPicConstants.QUE_ID,question.getId());
        return i>0;
    }

    @Override
    public PageVo<QuestionVo> queryByPage(PageDto pageDto) {
        IPage<Question> page = new Page<>(pageDto.getCurrentPage(),pageDto.getPageSize());
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("subject",pageDto.getQueryString());
        IPage<Question> questionIPage = questionMapper.selectPage(page,
                queryWrapper);
        List<QuestionVo> collect = questionIPage.getRecords().stream().map(
                question -> {
                    QuestionVo questionVo = new QuestionVo();
                    BeanUtils.copyProperties(question,questionVo);
                    return questionVo;
                }
        ).collect(Collectors.toList());
        return new PageVo<QuestionVo>(collect,(int)questionIPage.getTotal());
    }

    @Override
    public QuestionDto queryById(String id) {
        if(id!=null){
            Question question = questionMapper.selectById(id);
            QuestionDto questionDto = new QuestionDto();
            BeanUtils.copyProperties(question,questionDto);
            return questionDto;
        }else
        return new QuestionDto();
    }
}
